package com.iecas.launch;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.socket.nio.NioServer;
import com.iecas.handler.DefaultServerChannelHandler;
import com.iecas.runnner.DistributeRunner;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Server extends Frame {
    private NioServer server;
    Button start, stop, clear;
    TextArea logArea;
    Container bc, logC;
    DistributeRunner distributeRunner = new DistributeRunner();
    public Server() {
        this.setTitle("Server");
        this.setLayout(new BorderLayout());
        this.setSize(640, 480);
        bc = new Container();
        bc.setLayout(new FlowLayout());
        start = new Button("start");
        start.addActionListener(e -> start());
        bc.add(start);
        stop = new Button("stop");
        stop.addActionListener(e -> stop());
        bc.add(stop);
        clear = new Button("clear");
        clear.addActionListener(e -> clear());
        bc.add(clear);
        this.add(bc, BorderLayout.NORTH);
        logC = new Container();
        logC.setLayout(new BorderLayout());
        logArea = new TextArea();
        logC.add(logArea);
        this.add(logC, BorderLayout.CENTER);

        this.setVisible(true);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        this.setResizable(true);
    }

    private void clear() {
        logArea.setText("");
    }


    public void log(String message) {
        String text = logArea.getText();
        StringBuilder sb = new StringBuilder();
        sb.append(text);
        sb.append(DateUtil.now());
        sb.append(":");
        sb.append(message);
        sb.append("\n");

        String[] lines = text.split("\n");
        if (lines.length < 10){
            logArea.setText(sb.toString());
        }else {
            logArea.setText("");
        }
    }

    public void start() {
        if (ObjectUtil.isNull(server)) {
            server = new NioServer(20000);
            new Thread(() -> {
                log("Server listen on: [0.0.0.0/0.0.0.0:20000]");
                DefaultServerChannelHandler defaultChannelHandler = new DefaultServerChannelHandler();
                defaultChannelHandler.setServer(this);
                server.setChannelHandler(defaultChannelHandler).start();
            }).start();
        } else {
            log("Server already run");
        }
        distributeRunner.start();
    }

    public void stop() {
        if (ObjectUtil.isNotNull(server)) {
            server.close();
            server = null;
            log("Server closed");
        } else {
            log("Server not running");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->new Server().start());
    }
}
